<template>
  <div style="border: 1px solid #ccc">
    <Toolbar class="mybar" :editor="editorRef" :mode="mode" />
    <Editor 
      class="myeditor" 
      v-model="content"  
      :defaultConfig="editorConfig" 
      :mode="mode"
      @onCreated="handleCreated" 
    />
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted, defineProps, watch, defineEmits } from 'vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { useTokenStore } from '@/store/token'
import { getConfig } from '@/utils/config'

const tokenStore = useTokenStore()

const editorRef = shallowRef()
const mode = 'default'
const wangHeader = ref({
  token: tokenStore.token
})

const editorConfig = { MENU_CONF: {} }
editorConfig.MENU_CONF['uploadImage'] = {
  headers: wangHeader.value,
  server: getConfig('API_BASE_URL').replace(/\/?$/, '/') + 'files/wang/upload',
  fieldName: 'file'
}

onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor
}

// 定义 props 和 emits
const props = defineProps({
  editorContent: {
    type: String, // 修正为字符串类型
    default: ''
  }
})
const emit = defineEmits(['update:editorContent'])
// 内部响应式变量，接收 props 内容
// 初始化内部变量时增加容错
// const content = ref(props.editorContent || '')

// 监听 props 变化，同步到内部变量
// watch(
//   () => props.editorContent,
//   (newVal) => {
//     content.value = newVal || '' // 确保是字符串
//   },
//   { immediate: true }
// )

// // 监听内部内容变化，同步到父组件
// watch(
//   () => content.value,
//   (newVal) => {
//     emit('update:editorContent', newVal)
//   }
// )
</script>

<style scoped>
.mybar {
  border-bottom: 1px solid #ccc;
}
.myeditor {
  height: 40vh;
  overflow-y: auto; /* 建议改为 auto，内容过多时可滚动 */
}
</style>